import {
	reactive,
	ref,
	toRefs,
	getCurrentInstance,
	watch
} from "vue"
import {
	onReady,
	onLoad,
	onShow,
	onShareAppMessage
} from '@dcloudio/uni-app'
import store from '@/store/index.js'; //需要引入store
function uuid(len, radix) {
	let chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
	let uuid = [],
		i;
	radix = radix || chars.length;
	if (len) {
		for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
	} else {
		let r;
		uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
		uuid[14] = '4';
		for (i = 0; i < 36; i++) {
			if (!uuid[i]) {
				r = 0 | Math.random() * 16;
				uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
			}
		}
	}
	return uuid.join('');
}

export default function() {
	const {
		proxy
	} = getCurrentInstance()
	const {
		baseUrl,
		baseImgUrl
	} = proxy;
	const uploadFileHost = `${baseUrl}/resources/public`;
	
	const navigationBarTitle = ref('');

	const chooseImage = (count) => {
		return new Promise(function(resolve, reject) {
			uni.chooseImage({
				count: count,
				sizeType: ['original', 'compressed'],
				sourceType: ['album'],
				success: function(res) {
					resolve(res);
				},
				fail(res) {
					reject(res);
					// uni.$u.toast(`上传失败，请重试`);
				}
			});
		})
	}
	const uploadFile = (path,formData) => {
		return new Promise(function(resolve, reject) {
			uni.uploadFile({
				url: uploadFileHost,
				filePath: path,
				name: 'file',
				formData: formData,
				success(res) {
					// console.log(res.data);
					if(typeof res.data == 'string'){
						res.data = JSON.parse(res.data)
					}
					if(res.statusCode == 200 && res.data && res.data.code == 200 && res.data.data){
						let img = res.data.data;
						img.fullUrl = baseImgUrl + img.url
						resolve(img);
					}else{
						reject(res);
					}
				},
				fail(res) {
					reject(res);
					// uni.$u.toast(`上传失败，请重试`);
				}
			});
		});
	}


	const uploadOssFile = async (path) => {
		return new Promise(async (resolve, reject) => {
			try {
				let {
					data
				} = await proxy.$u.api.commonGetOssPolicy();
				let path_arr = path.split('/');
				let fileName = path_arr[path_arr.length - 1];
				let objName = getObjName(data.dir, fileName)
				let formData = {
					key: objName,
					policy: data.policy,
					OSSAccessKeyId: data.accessid,
					signature: data.signature,
				}
				await uploadFile(data.host, formData, path);
				resolve(objName);
			} catch (e) {
				uni.$u.toast(`上传失败，请重试`)
				reject(e);
			}
		});
	}

	const getObjName = (dir, fileName) => {
		if (!dir) {
			dir = 'fcjy/'
		}
		if (!dir.endsWith("/")) {
			dir += '/'
		}
		const year = new Date().getFullYear();
		const month = String(new Date().getMonth() + 1).padStart(2, '0');
		const date = String(new Date().getDate()).padStart(2, '0');
		const formattedDate = `${year}/${month}/${date}/`;
		const timestamp = new Date().getTime();
		const _uuid = uuid(8);

		return `${dir}${formattedDate}${timestamp}${_uuid}${fileName}`
	}

	return {
		uploadOssFile,
		getObjName,
		chooseImage,
		uploadFile,
		uploadFileHost
	}
}